package com.bone.filter;

import com.alibaba.fastjson.JSONObject;
import com.bone.common.constant.Dict;
import com.bone.common.exception.BoneException;
import com.bone.common.util.JwtToken;
import com.bone.common.util.JwtUtil;
import com.bone.common.util.RedisUtils;
import com.bone.common.vo.Result;
import com.bone.modules.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author : WangKeKe
 * @date : 2020/8/14 10:40
 * Description : 登录鉴权拦截器
 */

@Slf4j
public class JwtFilter extends BasicHttpAuthenticationFilter {


    /**
     * 执行登录认证*
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        try {
            // 进行ShiroRealm的登录
            executeLogin(request, response);
        } catch (Exception e) {
            // 如果未通过刷新要求
            if (!refreshToken(request, response)) {
                // 如果在拦截器发生异常，则直接返回JSON数据
                log.info("出现异常信息:" + e.getMessage());
                this.response401(response, e.getMessage());
                return false;
            }
        }
        return true;
    }

    /**
     * 此处为AccessToken刷新，进行判断RefreshToken是否过期，未过期就返回新的AccessToken且继续正常访问
     */
    private boolean refreshToken(ServletRequest request, ServletResponse response) {
        ServletContext context = request.getServletContext();
        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
        //直接从IOC容器中获取UmsUserService以及redisUtil (filter是无法@Autowired的)
        ISysUserService sysUserService = ctx.getBean(ISysUserService.class);
        RedisUtils redisUtil = ctx.getBean(RedisUtils.class);
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        // 从请求头中获取token信息
        String token = httpServletRequest.getHeader(Dict.X_ACCESS_TOKEN);
        // 获取token中的用户ID信息
        String userId = JwtUtil.getUserId(token);
        if (userId == null) {
            return false;
        }
        // 由于token的密钥是用户的密码故需要通过用户名获取
        String password = sysUserService.getById(userId).getPassword();
        if (password == null) {
            return false;
        }
        String key = Dict.PREFIX_SHIRO_REFRESH_TOKEN + userId;
        // 首先判断缓存中是否存在refreshToken
        if (redisUtil.hasKey(key)) {
            // 再者判断当前token与缓存中的refreshToken的时间戳是否一致
            if (redisUtil.get(key).equals(JwtUtil.getClaim(token, Dict.CURRENT_TIME_MILLIS))) {
                // 获取当前最新时间戳
                String currentTimeMillis = String.valueOf(System.currentTimeMillis());
                // 如果一致重新生成token，并刷新缓存中的refreshToken
                token = JwtUtil.sign(userId, password, currentTimeMillis);
                redisUtil.set(key, currentTimeMillis, Dict.REFRESH_TOKEN_TIME);
                // 由于这个方法的触发条件是认证出现异常，所以这次要重新进行认证
                // 将新刷新的AccessToken再次进行Shiro的登录
                JwtToken jwtToken = new JwtToken(token);
                // 提交给UserRealm进行认证，如果错误他会抛出异常并被捕获，如果没有抛出异常则代表登入成功，返回true
                this.getSubject(request, response).login(jwtToken);
                // 最后将新的token放入响应头的指定字段中
                HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
                httpServletResponse.setHeader(Dict.X_ACCESS_TOKEN, token);
                httpServletResponse.setHeader("Access-Control-Expose-Headers", Dict.X_ACCESS_TOKEN);
                return true;
            }
        }
        return false;
    }

    /**
     * 无需转发，直接返回Response信息
     */
    private void response401(ServletResponse response, String msg) {
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        try (PrintWriter out = httpServletResponse.getWriter()) {
            String data = JSONObject.toJSONString(Result.noAuth(msg));
            out.append(data);
            out.flush();
        } catch (IOException e) {
            log.error("直接返回Response信息出现IOException异常:{}", e.getMessage());
            throw new BoneException("直接返回Response信息出现IOException异常:" + e.getMessage());
        }
    }

    /**
     * 拦截请求后，执行此方法生成Token并交于Shiro认证
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader(Dict.X_ACCESS_TOKEN);
        JwtToken jwtToken = new JwtToken(token);
        // 提交给realm进行登入，如果错误他会抛出异常并被捕获
        getSubject(request, response).login(jwtToken);
        // 如果没有抛出异常则代表登入成功，返回true
        return true;
    }


    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }
}
